import 'package:flutter/material.dart';

class StarRating extends StatefulWidget {
  final double rating;
  final double maxRating;
  final double size;
  final Color unselectedColor;
  final Color selectedColor;
  final Widget unselectedImage;
  final Widget selectedImage;
  final int count;
  StarRating(
      {super.key,
      required this.rating,
      this.maxRating = 10,
      this.size = 30,
      this.unselectedColor = const Color(0xffbbbbbb),
      this.selectedColor = const Color(0xffe0aa46),
      Widget? unselectedImage,
      Widget? selectedImage,
      this.count = 5})
      : unselectedImage = unselectedImage ??
            Icon(
              Icons.star,
              size: size,
              color: unselectedColor,
            ),
        selectedImage = selectedImage ??
            Icon(
              Icons.star,
              size: size,
              color: selectedColor,
            );

  @override
  State<StarRating> createState() => _StarRatingState();
}

class _StarRatingState extends State<StarRating> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Stack(children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: getUnSelectedImage(),
        ),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: getSelectedImage(),
        )
      ]),
    );
  }

  List<Widget> getUnSelectedImage() {
    return List.generate(widget.count, (index) => widget.unselectedImage);
  }

  List<Widget> getSelectedImage() {
    // 计算start的个数和剩余比例
    // 每一个星星的值
    double oneValue = widget.maxRating / widget.count;
    // 根据评分计算星星的个数
    int entireCount = (widget.rating / oneValue).floor();
    // 根据评分来计算取部分星星的值
    double leftValue = widget.rating - entireCount * oneValue;
    // 部分的值占比
    double leftRadio = leftValue / oneValue;

    // 获取star
    List<Widget> selectedImages = [];
    for (int i = 0; i < entireCount; i++) {
      selectedImages.add(widget.selectedImage);
    }

    // 裁剪
    Widget leftStar = ClipRect(
      clipper: MyRectClipper(leftRadio * widget.size),
      child: widget.selectedImage,
    );
    selectedImages.add(leftStar);
    return selectedImages;
  }
}

class MyRectClipper extends CustomClipper<Rect> {
  final double width;
  MyRectClipper(this.width);
  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, width, size.height);
  }

  @override
  bool shouldReclip(MyRectClipper oldClipper) {
    return width != oldClipper.width;
  }
}
